//
//  DYPhotoScanManager.m
//  PrivatePhoto
//
//  Created by PrivatePhoto Team on 2021.
//  Copyright © 2021年 PrivatePhoto Team. All rights reserved.6.
//

#import "DYPhotoScanManager.h"
#import "ImageCompare.h"
#import "DYAlbumScanModel.h"
@interface DYPhotoScanManager ()<PHPhotoLibraryChangeObserver>

@property (nonatomic, assign) NSUInteger sameSaveSpace;
@property (nonatomic, assign) NSUInteger similarSaveSpace;
@property (nonatomic, assign) NSUInteger screenshotsSaveSpace;
@property (nonatomic, assign) NSUInteger liveSaveSpace;

@property (nonatomic, strong) NSMutableArray *randomArray;

@property (nonatomic, strong) PHFetchResult *assetArr;
@property (nonatomic, strong) PHImageRequestOptions *imageOpt;
@property (nonatomic, strong) PHImageRequestOptions *sizeOpt;
@property (nonatomic, strong) CAAlbumScanItem *lastItem;

@property (nonatomic, strong) PHAsset *lastAsset;
@property (nonatomic, strong) NSData *imageData;
@property (nonatomic, strong) UIImage *lastImage;
@property (nonatomic, assign) BOOL lastSimilarPhoto;
@property (nonatomic, assign) BOOL lastSamePhoto;
@property (nonatomic, assign) BOOL lastSimilarLive;

/// 相似照片数据
//@property (nonatomic, strong) NSMutableArray *similarArr;
///// 截图照片数据
//@property (nonatomic, strong) NSMutableArray *screenshotsArr;
//
///// 相同照片数据
//@property (nonatomic, strong) NSMutableArray *samePhotsArr;
//
//@property (nonatomic, strong) NSMutableArray *livePhotsArr;

@property (nonatomic, copy) void (^completionHandler)(BOOL success, NSError *error);
@property (nonatomic, copy) void (^processHandler)(NSInteger current, NSInteger total);



@end

@implementation DYPhotoScanManager

//+ (DYPhotoScanManager *)shareManager {
//    static DYPhotoScanManager *mgr = nil;
//    static dispatch_once_t token;
//    dispatch_once(&token, ^{
//        mgr = [[DYPhotoScanManager alloc] init];
//    });
//    return mgr;
//}

#pragma mark - LibraryChange 相册变换通知

- (instancetype)init {
    self = [super init];
    if (self) {
        [[PHPhotoLibrary sharedPhotoLibrary] registerChangeObserver:self];
    }
    return self;
}

- (void)dealloc {
    [[PHPhotoLibrary sharedPhotoLibrary] unregisterChangeObserver:self];
}

- (void)photoLibraryDidChange:(PHChange *)changeInstance {
    // 筛选出没必要的变动
    PHFetchResultChangeDetails *collectionChanges =
    [changeInstance changeDetailsForFetchResult:self.assetArr];
    if (collectionChanges == nil || self.notificationStatus != CAPhotoNotificationStatusDefualt) {
        return;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([self.delegate respondsToSelector:@selector(clearPhotoLibraryDidChange)]) {
            [self.delegate clearPhotoLibraryDidChange];
        }
    });
}

#pragma mark - GetImage 获取图片

// 加载照片
- (void)loadPhotoWithProcess:(void (^)(NSInteger current, NSInteger total))process
           completionHandler:(void (^)(BOOL success, NSError *error))completion {
    [self resetTagData];
    self.processHandler = process;
    self.completionHandler = completion;
    
    // 获取当前App的相册授权状态
    PHAuthorizationStatus authorizationStatus = [PHPhotoLibrary authorizationStatus];
    // 判断授权状态
    if (authorizationStatus == PHAuthorizationStatusAuthorized) {
        // 如果已经授权, 获取图片
        [self getAllAsset];
    }
    // 如果没决定, 弹出指示框, 让用户选择
    else if (authorizationStatus == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            // 如果用户选择授权, 则获取图片
            if (status == PHAuthorizationStatusAuthorized) {
                [self getAllAsset];
            }
        }];
    } else {
        [self noticeAlert];
    }
}

// 获取相簿中的PHAsset对象
- (void)getAllAsset {
    // 获取所有资源的集合，并按资源的创建时间排序
    PHFetchOptions *options = [[PHFetchOptions alloc] init];
    options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate"
                                                              ascending:NO]];
    PHFetchResult *result = [PHAsset fetchAssetsWithOptions:options];
    self.assetArr = result;
    [self requestImageWithIndex:0];
}

- (void)handleImageCountForRequestWithIndex:(NSInteger)index{
   
    if (index >= self.assetArr.count) {
        [self loadCompletion];
        self.completionHandler(YES, nil);
        return;
    }
    
    NSInteger totalCount = self.assetArr.count;
    NSInteger normalCount = totalCount*3/10;
 
    if (index > normalCount && (index+5 ) <= self.assetArr.count) {
        if (!self.lastSimilarPhoto) {
          [self.randomArray removeAllObjects];
            while ([self.randomArray count] < 5) {
                int r = arc4random() % 5;
                [self.randomArray addObject:[self.assetArr objectAtIndex:index+r]];
            }
            [self requestImageWithAsset:self.randomArray.firstObject];
        }else{
            [self requestImageWithIndex:index];
        }
    }else{
        [self requestImageWithIndex:index];
    }
    
}

- (void)requestImageWithAsset:(PHAsset *)asset{
    NSInteger index = [self.assetArr indexOfObject:asset];
    self.processHandler(index, self.assetArr.count);

    if (index >= self.assetArr.count) {
        [self loadCompletion];
        self.completionHandler(YES, nil);
        return;
    }
    
    // 筛选本地图片，过滤视频、iCloud图片
    if (asset.mediaType != PHAssetMediaTypeImage || asset.sourceType != PHAssetSourceTypeUserLibrary) {
        [self requestImageWithIndex:index+1];
        return;
    }
    // 获取缩率图
    PHImageManager *mgr = [PHImageManager defaultManager];
    __weak typeof(self) weakSelf = self;
    [mgr requestImageForAsset:asset
                   targetSize:CGSizeMake(125, 125)
                  contentMode:PHImageContentModeDefault
                      options:self.imageOpt
                resultHandler:^(UIImage *result, NSDictionary *info) {
                    [weakSelf getImageSizeWithIndex:index
                                              image:result];
                }];
}

- (void)requestImageWithIndex:(NSInteger)index {

    self.processHandler(index, self.assetArr.count);

    if (index >= self.assetArr.count) {
        [self loadCompletion];
        self.completionHandler(YES, nil);
        return;
    }
    
    // 筛选本地图片，过滤视频、iCloud图片
    PHAsset *a_sset = self.assetArr[index];
    if (a_sset.mediaType != PHAssetMediaTypeImage || a_sset.sourceType != PHAssetSourceTypeUserLibrary) {
        [self requestImageWithIndex:index+1];
        return;
    }
    // 获取缩率图
    PHImageManager *mgr = [PHImageManager defaultManager];
    __weak typeof(self) weakSelf = self;
    [mgr requestImageForAsset:a_sset
                   targetSize:CGSizeMake(125, 125)
                  contentMode:PHImageContentModeDefault
                      options:self.imageOpt
                resultHandler:^(UIImage *result, NSDictionary *info) {
                    [weakSelf getImageSizeWithIndex:index
                                              image:result];
                }];
}

// 获取原图片大小
- (void)getImageSizeWithIndex:(NSInteger)index
                        image:(UIImage *)image {
    __weak typeof(self) weakSelf = self;
    PHImageManager *mgr = [PHImageManager defaultManager];

    if (@available(iOS 13, *)) {
        [mgr requestImageDataAndOrientationForAsset:self.assetArr[index] options:self.sizeOpt resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, CGImagePropertyOrientation orientation, NSDictionary * _Nullable info) {
            [weakSelf dealImageWithIndex:index image:image imageData:imageData];
        }];
    } else {
     
            [mgr requestImageDataForAsset:self.assetArr[index]
                                  options:self.sizeOpt
                            resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
                [weakSelf dealImageWithIndex:index image:image imageData:imageData];
            }];
        
    }
    
}

#pragma mark - DealImage 处理图片
// 处理相片
- (void)dealImageWithIndex:(NSInteger)index
                     image:(UIImage *)image
                 imageData:(NSData *)imageData {
  
    PHAsset *asset = self.assetArr[index];
    if (index > 0) {
        [self handleCompareEventWithAsset:asset image:image imgData:imageData index:index];
    }else{
        [self setLastDataWithAsset:asset image:image imgData:imageData index:index];
    }

}

- (void)handleCompareEventWithAsset:(PHAsset *)asset image:(UIImage *)image imgData:(NSData *)imgData index:(NSInteger)index{
    if ([self.imageData isEqual:imgData]) {
        [self updateSameArrWithAsset:asset imageData:imgData];
        self.lastSamePhoto = YES;
    }else{
        self.lastSamePhoto = NO;
    }
    
    BOOL isSameTime = [self isSameTime:self.lastAsset.creationDate date2:asset.creationDate];
    // 相似图片
    if (self.lastAsset && isSameTime) {
            BOOL isLike = [ImageCompare isImage:self.lastImage likeImage:image];
            if (isLike) {
                [self updateSimilarArrWithAsset:asset imageData:imgData];
                self.lastSimilarPhoto = YES;
            }else {
                self.lastSimilarPhoto = NO;
            }
    }else{
        self.lastSimilarPhoto = NO;
    }

    // 截屏图片
    if (asset.mediaSubtypes == PHAssetMediaSubtypePhotoScreenshot) {
        [self updateScreenShotsWithAsset:asset
                               imageData:imgData
                                lastDict:@{}];
    }
    [self setLastDataWithAsset:asset image:image imgData:imgData index:index];
}

- (void)setLastDataWithAsset:(PHAsset *)asset image:(UIImage *)lastImage imgData:(NSData *)imgData index:(NSInteger)index{
    self.lastAsset = asset;
    self.lastImage = lastImage;
    self.imageData = imgData;
    [self handleImageCountForRequestWithIndex:index+1];
}
/*
// 重复图片数据
- (void)handleSamePhotoDataEventWithIndex:(NSInteger)index
                                    asset:(PHAsset *)asset
                                    image:(UIImage *)image
                                imageData:(NSData *)imageData
                                 sameTime:(BOOL)isSameTime{
    
    if ([self.imageData isEqual:imageData]) {
        DYAlbumScanModel *lastModel = self.samePhotsArr.lastObject;
        if (lastModel && !isSameTime) {lastModel = nil;}
        [self updateSameArrWithAsset:asset
                           imageData:imageData
                            lastDict:lastModel];
        self.lastItem.asset = asset;
        self.lastItem.itemSpace = imageData.length;
//        self.lastAsset = asset;
        self.lastImage = image;
        [self handleImageCountForRequestWithIndex:index+1];
        self.lastSame = YES;
        return;
    }
}

- (void)updateSameArrWithAsset:(PHAsset *)asset
                        imageData:(NSData *)imageData
                      lastDict:(DYAlbumScanModel *)lastModel{
    
    CAAlbumScanItem *item = [[CAAlbumScanItem alloc] init];
    item.asset = asset;
    item.itemSpace = imageData.length;
    
    if (!lastModel) {
        NSString *keyStr = [self stringWithDate:asset.creationDate];
        lastModel = [[DYAlbumScanModel alloc] init];
        lastModel.creationDate = keyStr;
        if (self.lastItem.asset) {
            [lastModel.itemArray addObject:self.lastItem];
        }
        [lastModel.itemArray addObject:item];
        [self.samePhotsArr addObject:lastModel];
    } else {
        [lastModel.itemArray addObject:self.lastItem];
        [lastModel.itemArray addObject:item];
        [self.samePhotsArr replaceObjectAtIndex:self.samePhotsArr.count-1
                                       withObject:lastModel];
    }
    self.sameSaveSpace = self.sameSaveSpace + imageData.length;
    
}

// 相似图片数据
- (void)handleSimilarPhotoDataEventWithAsset:(PHAsset *)asset
                                    image:(UIImage *)image
                                imageData:(NSData *)imageData{
    
    BOOL isSameTime = [self isSameTime:self.lastItem.asset.creationDate date2:asset.creationDate];
    if (self.lastItem.asset && isSameTime) {
         BOOL isLike = [ImageCompare isImage:self.lastImage likeImage:image];
         if (isLike) {
              [self updateSimilarArrWithAsset:asset imageData:imageData];
              self.lastSame = YES;
            }else {
              self.lastSame = NO;
            }
    }else{
        self.lastSame = NO;
    }
    
}

- (void)updateSimilarArrWithAsset:(PHAsset *)asset imageData:(NSData *)imageData {
    DYAlbumScanModel *lastModel = self.similarArr.lastObject;
    if (!self.lastSame) {lastModel = nil;}
    CAAlbumScanItem *item = [[CAAlbumScanItem alloc] init];
    item.asset = asset;
    item.itemSpace = imageData.length;
    if (!lastModel) {
        NSString *keyStr = [self stringWithDate:asset.creationDate];
        lastModel = [[DYAlbumScanModel alloc] init];
        lastModel.creationDate = keyStr;
        if (self.lastItem.asset) {
            [lastModel.itemArray addObject:self.lastItem];
        }
        [lastModel.itemArray addObject:item];
        
        [self.similarArr addObject:lastModel];
    }else{
        [lastModel.itemArray addObject:self.lastItem];
        [lastModel.itemArray addObject:item];
        [self.similarArr replaceObjectAtIndex:self.similarArr.count-1
                               withObject:lastModel];
        
    }
    self.similarSaveSpace = self.similarSaveSpace + imageData.length;
}

// 截屏图片数据
- (void)updateScreenShotsWithAsset:(PHAsset *)asset
                         imageData:(NSData *)imageData
                          lastDict:(NSDictionary *)lastDict{
    CAAlbumScanItem *item = [[CAAlbumScanItem alloc] init];
    item.asset = asset;
    item.itemSpace = imageData.length;
    [self.screenshotsArr addObject:item];
    self.screenshotsSaveSpace = self.screenshotsSaveSpace + imageData.length;
}

// Live图片数据
- (void)handleLivePhotoWithAsset:(PHAsset *)asset
                           image:(UIImage *)image
                       imageData:(NSData *)imageData
                        sameTime:(BOOL)isSameTime{
    
    if (self.lastItem.asset && isSameTime) {
        BOOL isLike = [ImageCompare isImage:self.lastImage likeImage:image];
        if (isLike) {
            DYAlbumScanModel *lastModel = self.livePhotsArr.lastObject;
            if (lastModel && !isSameTime) {lastModel = nil;}
            [self updateLivePhotsWithAsset:asset
                            imageData:imageData
                            lastDict:lastModel];
        }

    }
    
}

- (void)updateLivePhotsWithAsset:(PHAsset *)asset
                         imageData:(NSData *)imageData
                          lastDict:(DYAlbumScanModel *)lastModel{
    CAAlbumScanItem *item = [[CAAlbumScanItem alloc] init];
    item.asset = asset;
    item.itemSpace = imageData.length;
    
    if (!lastModel) {
   
        NSString *keyStr = [self stringWithDate:asset.creationDate];
        lastModel = [[DYAlbumScanModel alloc] init];
        lastModel.creationDate = keyStr;
        if (self.lastItem.asset) {
            [lastModel.itemArray addObject:self.lastItem];
        };
        [lastModel.itemArray addObject:item];
        [self.livePhotsArr addObject:lastModel];
        
    } else {
        [lastModel.itemArray addObject:self.lastItem];
        [lastModel.itemArray addObject:item];
        [self.livePhotsArr replaceObjectAtIndex:self.livePhotsArr.count-1
                                       withObject:lastModel];
        
    }
    self.liveSaveSpace = self.liveSaveSpace + imageData.length;
}
*/

// 更新重复图片数据
- (void)updateSameArrWithAsset:(PHAsset *)asset imageData:(NSData *)imageData{
    NSDictionary *item = @{@"asset":asset, @"space":@(imageData.length)};
    NSDictionary *lastDict = self.samePhotsArr.lastObject;
    if (!self.lastSamePhoto) {
        lastDict = nil;
    }
    if (!lastDict) {

        NSString *keyStr = [self stringWithDate:self.lastAsset.creationDate];
        if (!self.lastAsset) {
            lastDict = @{keyStr: [@[item] mutableCopy]};
        }else{
            NSDictionary *lastItem = @{@"asset":self.lastAsset, @"space":@(self.imageData.length)};
            lastDict = @{keyStr:[@[lastItem,item] mutableCopy]};
        };
        [self.samePhotsArr addObject:lastDict];
    } else {
        NSMutableArray *itemArr = lastDict.allValues.lastObject;
//        NSDictionary *lastItem = @{@"asset":self.lastAsset, @"space":@(self.imageData.length)};
//        [itemArr addObject:lastItem];//
        [itemArr addObject:item];//
        lastDict = @{lastDict.allKeys.lastObject : itemArr};
        [self.samePhotsArr replaceObjectAtIndex:self.samePhotsArr.count-1
                                       withObject:lastDict];
        
    }
    self.sameSaveSpace = self.sameSaveSpace + imageData.length;
    
}

// 更新相似图片数据
- (void)updateSimilarArrWithAsset:(PHAsset *)asset imageData:(NSData *)imageData {
    
    NSDictionary *item = @{@"asset":asset, @"space":@(imageData.length)};
    
    NSDictionary *lastDict = self.similarArr.lastObject;
    if (!self.lastSimilarPhoto) {
        lastDict = nil;
    }
    
    if (!lastDict) {

        NSString *keyStr = [self stringWithDate:self.lastAsset.creationDate];//asset.creationDate
        if (!self.lastAsset) {
            lastDict = @{keyStr: [@[item] mutableCopy]};
        }else{
            NSDictionary *lastItem = @{@"asset":self.lastAsset, @"space":@(self.imageData.length)};
            lastDict = @{keyStr:[@[lastItem,item] mutableCopy]};
        }
        [self.similarArr addObject:lastDict];
    }else{

        NSMutableArray *itemArr = lastDict.allValues.lastObject;
//        NSDictionary *lastItem = @{@"asset":self.lastAsset, @"space":@(self.imageData.length)};
//        [itemArr addObject:lastItem];//
        [itemArr addObject:item];//
        lastDict = @{lastDict.allKeys.lastObject : itemArr};
        [self.similarArr replaceObjectAtIndex:self.similarArr.count-1
                               withObject:lastDict];
        
    }
    self.similarSaveSpace = self.similarSaveSpace + imageData.length;
}

// 更新截屏图片数据
- (void)updateScreenShotsWithAsset:(PHAsset *)asset
                         imageData:(NSData *)imageData
                          lastDict:(NSDictionary *)lastDict{
    NSDictionary *item = @{@"asset":asset, @"space":@(imageData.length)};
    [self.screenshotsArr addObject:item];
    self.screenshotsSaveSpace = self.screenshotsSaveSpace + imageData.length;
}

// 更新Live图片数据
- (void)updateLivePhotsWithAsset:(PHAsset *)asset
                         imageData:(NSData *)imageData
                          lastDict:(NSDictionary *)lastDict{
    NSDictionary *item = @{@"asset":asset, @"space":@(imageData.length)};
    if (!lastDict) {
        NSString *keyStr = [self stringWithDate:asset.creationDate];
        if (!self.lastAsset) {
            lastDict = @{keyStr: [@[item] mutableCopy]};
        }else{
            NSDictionary *lastItem = @{@"asset":self.lastAsset, @"space":@(self.imageData.length)};
            lastDict = @{keyStr:[@[lastItem,item] mutableCopy]};
        }
//        lastDict = @{keyStr :!self.lastAsset ? [@[asset] mutableCopy]: [@[self.lastAsset,asset] mutableCopy]};
        [self.livePhotsArr addObject:lastDict];
        
    } else {
        NSMutableArray *itemArr = lastDict.allValues.lastObject;
        NSDictionary *lastItem = @{@"asset":self.lastAsset, @"space":@(self.imageData.length)};
        [itemArr addObject:lastItem];//
        [itemArr addObject:item];//
        lastDict = @{lastDict.allKeys.lastObject : itemArr};
        [self.livePhotsArr replaceObjectAtIndex:self.livePhotsArr.count-1
                                       withObject:lastDict];
        
    }
    self.liveSaveSpace = self.liveSaveSpace + imageData.length;
}


// 重置数据
- (void)resetTagData {
    self.similarArr = nil;
    self.similarInfo = nil;
    self.similarSaveSpace = 0;
    self.similarData = nil;
    self.screenshotsArr = nil;
    self.screenshotsInfo = nil;
    self.screenshotsSaveSpace = 0;
    self.screenshotsData = nil;
    
    self.samePhotsArr = nil;
    self.samePhotsInfo = nil;
    self.samePhotsData = nil;
    self.sameSaveSpace = 0;
    
    self.livePhotsArr = nil;
    self.livePhotsInfo = nil;
    self.livePhotsData = nil;
    self.liveSaveSpace = 0;
    
    self.totalSaveSpace = 0;
}

// 加载完成
- (void)loadCompletion {
    
//    self.similarData = [self getInfoWithDataArray:self.similarArr
//                                        saveSpace:self.similarSaveSpace
//                                        cleanType:CAClearAlbumTypeSimilar];
    self.similarInfo = [self getInfoWithDataArr:self.similarArr
                                      saveSpace:self.similarSaveSpace];

    self.screenshotsInfo = [self getInfoWithScreenshotsArr:self.screenshotsArr
                                          saveSpace:self.screenshotsSaveSpace];
//    self.screenshotsData = [self getInfoWithScreenshots:self.screenshotsArr
//                                              saveSpace:self.screenshotsSaveSpace
//                                              cleanType:CAClearAlbumTypeScreenshots];
////
//    self.samePhotsData = [self getInfoWithDataArray:self.samePhotsArr
//                                          saveSpace:self.sameSaveSpace
//                                          cleanType:CAClearAlbumTypeSamePhoto];
    self.samePhotsInfo = [self getInfoWithDataArr:self.samePhotsArr
                                        saveSpace:self.sameSaveSpace];
    
    for (NSDictionary *dict in self.similarArr) {
        NSArray *array = dict.allValues.lastObject;
        NSDictionary *itemDict = array.firstObject;
        PHAsset *asset = itemDict[@"asset"];
        if (asset.mediaSubtypes == PHAssetMediaSubtypePhotoLive) {
            [self.livePhotsArr addObject:dict];
            for (NSDictionary *dic in array) {
                self.liveSaveSpace = self.liveSaveSpace + [dic[@"space"] longLongValue];
            }
        }
        
        
    }
    

    self.livePhotsInfo = [self getInfoWithDataArr:self.livePhotsArr
                                        saveSpace:self.liveSaveSpace];
//    self.livePhotsData = [self getInfoWithDataArray:self.livePhotsArr
//                                          saveSpace:self.liveSaveSpace
//                                          cleanType:CAClearAlbumTypeLivePhoto];
    
    self.totalSaveSpace = self.similarSaveSpace + self.sameSaveSpace + self.screenshotsSaveSpace+self.liveSaveSpace;
    
    NSLog(@"相似照片可省 ：%.2fMB", self.similarSaveSpace / 1024.0 / 1024.0);
    NSLog(@"截屏照片可省 ：%.2fMB", self.screenshotsSaveSpace / 1024.0 / 1024.0);
    NSLog(@"压缩照片可省 ：%.2fMB", self.sameSaveSpace / 1024.0 / 1024.0);
    NSLog(@"***ZJH 加载完成");

}

#pragma mark - Private 私有方法

- (NSDictionary *)getInfoWithDataArr:(NSArray *)dataArr
                           saveSpace:(NSUInteger)saveSpace {
    NSUInteger similarCount = 0;
    for (NSDictionary *dict in dataArr) {
        NSArray *arr = dict.allValues.lastObject;
        similarCount = similarCount + arr.count;
    }
    return @{@"count":@(similarCount), @"saveSpace" : @(saveSpace)};
}
//
//- (CAPhotoScanInfo *)getInfoWithDataArray:(NSArray *)dataArr
//                           saveSpace:(NSUInteger)saveSpace
//                                cleanType:(CAClearAlbumType)type
//{
//    NSUInteger similarCount = 0;
//    for (DYAlbumScanModel *model in dataArr) {
//        NSArray *arr = [model.itemArray copy];
//        if (arr.firstObject) {
//            continue;
//        }
//        similarCount = similarCount + arr.count;
//    }
////    for (NSDictionary *dict in dataArr) {
////        NSArray *arr = dict.allValues.lastObject;
////        similarCount = similarCount + arr.count;
////    }
//    CAPhotoScanInfo *info = [[CAPhotoScanInfo alloc] init];
//    [info.InfoArray removeAllObjects];
//    [info.InfoArray addObjectsFromArray:dataArr];
//    info.saveSpace = saveSpace;
//    info.count = similarCount;
//    info.cleanType = type;
//    info.is_seleted = YES;
//    return info;
//}

- (NSDictionary *)getInfoWithScreenshotsArr:(NSArray *)dataArr
                           saveSpace:(NSUInteger)saveSpace {


    return @{@"count":@(dataArr.count), @"saveSpace" : @(saveSpace)};
}

//- (CAPhotoScanInfo *)getInfoWithScreenshots:(NSArray *)dataArr
//                           saveSpace:(NSUInteger)saveSpace
//                                  cleanType:(CAClearAlbumType)type
//{
//    CAPhotoScanInfo *info = [[CAPhotoScanInfo alloc] init];
//    [info.InfoArray removeAllObjects];
//    [info.InfoArray addObjectsFromArray:dataArr];
//    info.saveSpace = saveSpace;
//    info.cleanType = type;
//    info.count = dataArr.count;
//    info.is_seleted = YES;
//    return info;
//}

// 是否为同一天
- (BOOL)isSameDay:(NSDate *)date1 date2:(NSDate *)date2 {
    if (!date1 || !date2) {
        return NO;
    }
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay;
    NSDateComponents *comp1 = [calendar components:unitFlags fromDate:date1];
    NSDateComponents *comp2 = [calendar components:unitFlags fromDate:date2];
    return  [comp1 day] == [comp2 day] &&
            [comp1 month] == [comp2 month] &&
            [comp1 year]  == [comp2 year];
}
//是否相隔5分钟
- (BOOL)isSameTime:(NSDate *)date1 date2:(NSDate *)date2 {
    if (!date1 || !date2) {return NO;}

    long long t1 = [date1 longlongTimeIntervalSince1970];
    long long t2 = [date2 longlongTimeIntervalSince1970];
    long long tt = t1 - t2;
    long long min = [[NSNumber numberWithDouble:tt] longLongValue];
    return min <300;
}

// NSDate转NSString
- (NSString *)stringWithDate:(NSDate *)date {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    return [dateFormatter stringFromDate:date];
}

// 开启权限提示
- (void)noticeAlert {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:@"此功能需要相册授权"
                                        message:@"请您在设置系统中打开授权开关"
                                 preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *left = [UIAlertAction actionWithTitle:@"取消"
                                                   style:UIAlertActionStyleCancel
                                                 handler:nil];
    UIAlertAction *right = [UIAlertAction actionWithTitle:@"前往设置"
                                                    style:UIAlertActionStyleDefault
                                                  handler:^(UIAlertAction * _Nonnull action) {
                                                      NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                                                      [[UIApplication sharedApplication] openURL:url];
                                                  }];
    [alert addAction:left];
    [alert addAction:right];
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    [vc presentViewController:alert animated:YES completion:nil];
}

#pragma mark - Getter 懒加载

- (NSMutableArray *)similarArr {
    if (!_similarArr) {
        _similarArr = [NSMutableArray array];
    }
    return _similarArr;
}

- (NSMutableArray *)screenshotsArr {
    if (!_screenshotsArr) {
        _screenshotsArr = [NSMutableArray array];
    }
    return _screenshotsArr;
}

- (NSMutableArray *)samePhotsArr {
    if (!_samePhotsArr) {
       _samePhotsArr = [NSMutableArray array];
    }
    return _samePhotsArr;
}

- (NSMutableArray *)livePhotsArr {
    if (!_livePhotsArr) {
        _livePhotsArr = [NSMutableArray array];
    }
    return _livePhotsArr;
}


- (NSMutableArray *)randomArray {
    if (!_randomArray) {
        _randomArray = [NSMutableArray array];
    }
    return _randomArray;
}

- (CAAlbumScanItem *)lastItem{
    if (!_lastItem) {
        _lastItem = [[CAAlbumScanItem alloc] init];
    }
    return _lastItem;
}

- (PHImageRequestOptions *)imageOpt {
    if (!_imageOpt) {
        _imageOpt = [[PHImageRequestOptions alloc] init];
        // resizeMode 属性控制图像的剪裁
        _imageOpt.resizeMode = PHImageRequestOptionsResizeModeNone;
        // deliveryMode 则用于控制请求的图片质量
        _imageOpt.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
    }
    return _imageOpt;
}

- (PHImageRequestOptions *)sizeOpt {
    if (!_sizeOpt) {
        _sizeOpt = [[PHImageRequestOptions alloc] init];
        _sizeOpt.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        _sizeOpt.resizeMode = PHImageRequestOptionsResizeModeExact;
    }
    return _sizeOpt;
}

+ (void)tipWithMessage:(NSString *)str {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:@"提示"
                                        message:str
                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action =
    [UIAlertAction actionWithTitle:@"确定"
                             style:UIAlertActionStyleCancel
                           handler:nil];
    [alert addAction:action];
    
    UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    [vc presentViewController:alert animated:YES completion:nil];
}

@end

@implementation CAPhotoScanInfo

- (instancetype)init{
    if (self = [super init]) {
        self.InfoArray = [NSMutableArray new];
        self.seletedPicArray = [NSMutableArray new];
    }
    return self;
}

@end
